import median from "./median.js";

/**
 * [中位绝对偏差](http://en.wikipedia.org/wiki/Median_absolute_deviation)是一种
 * 鲁棒的统计离散度量。相比标准差，它对异常值更具抵抗力。
 *
 * @param {Array<number>} x 输入数组
 * @returns {number} 中位绝对偏差
 * @example
 * medianAbsoluteDeviation([1, 1, 2, 2, 4, 6, 9]); // => 1
 */
function medianAbsoluteDeviation(x) {
    const medianValue = median(x);
    const medianAbsoluteDeviations = [];

    // 计算每个数据点与中位数的绝对偏差
    for (let i = 0; i < x.length; i++) {
        medianAbsoluteDeviations.push(Math.abs(x[i] - medianValue));
    }

    // 返回这些绝对偏差的中位数
    return median(medianAbsoluteDeviations);
}

export default medianAbsoluteDeviation;
